package structuralPatterns.composite;

import java.util.ArrayList;
import java.util.List;

interface Component {
    void operation();  // 业务方法
    //可以把add和remove方法放到Component接口中，这样所有的叶子节点和树枝节点都有相同的接口，客户端可以一致地对待所有的对象。
}

class Leaf implements Component {
    private String name;

    public Leaf(String name) {
        this.name = name;
    }

    @Override
    public void operation() {
        // 实现业务方法
        System.out.println("Leaf operation + " + name);
    }
}

class Composite implements Component {
    private List<Component> components = new ArrayList<>();

    @Override
    public void operation() {
        // 实现业务方法
        for (Component component : components) {
            component.operation();
        }
    }

    public void add(Component component) {
        components.add(component);
    }

    public void remove(Component component) {
        components.remove(component);
    }
}

public class CompositePattern {
    public static void main(String[] args) {
        Composite root = new Composite();
        root.add(new Leaf("Leaf1"));
        root.add(new Leaf("Leaf2"));
        Composite branch = new Composite();
        branch.add(new Leaf("Leaf3"));
        branch.add(new Leaf("Leaf4"));
        root.add(branch);
        root.operation();
    }
}
